package com.markus.code.exam.xiecheng;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Author:markusZhang
 * Date:Create in 2020/8/15 19:27
 * todo:
 */
class WorkflowNode {
    String nodeId;
    int timeoutMillis;
    List<WorkflowNode> nextNodes;
    boolean initialised;

    public static WorkflowNode load(String value) {
        // Create head node;
        Map<String, WorkflowNode> map = new HashMap<>();
        WorkflowNode head = new WorkflowNode("HEAD", 0, null);
        map.put(head.nodeId, head);

        for (String nodeValue : value.split("\\|")) {
            String[] properties = nodeValue.split("\\`");
            WorkflowNode node = map.get(properties[0]);

            node.timeoutMillis = Integer.parseInt(properties[1]);
            node.initialised = true;

            // Check next nodes
            if (properties[2].equals("END")) {
                continue;
            }
            node.nextNodes = Arrays.stream(properties[2].split(","))
                    .map(p -> new WorkflowNode(p, 0, null))
                    .collect(Collectors.toList());
            node.nextNodes.forEach(p -> map.put(p.nodeId, p));

            map.put(node.nodeId, node);
        }

        return head;
    }

    public WorkflowNode(String nodeId, int timeoutMillis, List<WorkflowNode> nextNodes) {
        this.nodeId = nodeId;
        this.timeoutMillis = timeoutMillis;
        this.nextNodes = nextNodes;
    }
}

public class Main1
{
    public static class Info{
        private int time;
        private boolean isInit;
        public Info(int time,boolean isInit){
            this.time = time;
            this.isInit = isInit;
        }
    }
    public static void main(String args[])
    {
        Scanner cin = new Scanner(System.in);
        while (cin.hasNext())
        {
            try{
                WorkflowNode node = WorkflowNode.load(cin.next());
                System.out.println(timeout(node));
            }catch(Exception e){
                System.out.println(-1);
            }
        }
    }
    private static int timeout(WorkflowNode head){
        if (head == null){
            return -1;
        }
        Info info = process(head);
        return info.isInit?info.time:-1;
    }
    private static Info process(WorkflowNode x){
        if (x.nextNodes == null){
            return new Info(x.timeoutMillis,x.initialised);
        }
        int time = x.timeoutMillis;
        //默认被初始化了
        boolean isInit = true;
        int sonMaxTime = 0;
        for (WorkflowNode nextNode : x.nextNodes) {
            Info sonInfo = process(nextNode);
            if (!sonInfo.isInit){
                isInit = false;
            }
            sonMaxTime = sonMaxTime<sonInfo.time?sonInfo.time:sonMaxTime;
        }
        return new Info(time+sonMaxTime,isInit);
    }
}
